package com.yixuan.mt.console.controller;

import com.yixuan.mt.common.entity.Objects;
import com.yixuan.mt.common.response.Result;
import com.yixuan.mt.common.request.UploadRequest;
import com.yixuan.mt.common.service.ObjectsService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.yixuan.mt.common.exception.HttpBadRequestException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/op/objects")
public class ObjectsController {

    @Autowired
    private ObjectsService objectsService;

    /**
     * 上传文件
     * @throws IOException 操作文件失败
     * @throws HttpBadRequestException 在插入对象时，对象名已存在的情况
     */
    @PostMapping("/upload")
    public Result<?> upload(@Valid @ModelAttribute UploadRequest uploadRequest) throws IOException {
        objectsService.upload(uploadRequest);
        return Result.success();
    }

    /**
     * 新建文件夹
     */
    @PostMapping("/folder")
    public Result<?> postFolder(@RequestBody String folderPath) {
        objectsService.postFolder(folderPath);
        return Result.success();
    }

    /**
     * 删除对象
     */
    @DeleteMapping("/{name}/{ids}")
    public Result<?> deleteObjects(@PathVariable String name, @PathVariable List<Integer> ids) {
        objectsService.deleteObjects(name, ids);
        return Result.success();
    }


    /**
     * 获取对象列表
     * @param lastId 上一次获取的最后一个对象对象的id
     * @param parentPath 父级路径
     */
    @GetMapping
    public Result<List<Objects>> getObjects(Integer lastId, String parentPath) throws IOException {
        return Result.success(objectsService.getObjects(lastId, parentPath));
    }

    /**
     * 下载文件
     * @throws FileNotFoundException 文件不存在
     */
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> download(String objectPath) throws FileNotFoundException {
        return objectsService.download(objectPath);
    }


}
